import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wanandroid_flutter/bean/app_response.dart';
import 'package:wanandroid_flutter/network/api.dart';
import 'package:wanandroid_flutter/network/request_util.dart';

import '../bean/articles_bean.dart';
import '../bean/system_screen_bean.dart';

class SystemController extends GetxController
    with GetSingleTickerProviderStateMixin {
  var tabs = <SystemScreenBean>[].obs;

  var selectIndex = 0.obs;

  var _pageIndex = 0;

  TabController? tabCtr;

  var articleList = <ArticleBean>[].obs;

  final controller = EasyRefreshController(
      controlFinishRefresh: true, controlFinishLoad: true);

  @override
  Future<void> onInit() async {
    super.onInit();
    await httpSystemScreen();
    tabCtr = TabController(length: tabs.length, vsync: this);
    tabCtr?.addListener(() {
      //切换选中的Tab监听
      selectIndex.value = 0;
      refreshRequest();
    });
  }

  ///体系筛选
  httpSystemScreen() async {
    AppResponse<List<SystemScreenBean>> sysScreenRes =
        await HttpGo.instance.get(Api.systemScreen);
    if (sysScreenRes.isSuccessful) {
      tabs.value = sysScreenRes.data ?? [];
      refreshRequest();
    }
  }

  ///体系文章列表
  Future<IndicatorResult> httpArticleList() async {
    int firstSelect = tabCtr?.index ?? 0;
    int cid = tabs[firstSelect].children[selectIndex.value].id ?? 0;
    AppResponse<ArticleData> articleRes = await HttpGo.instance
        .get("${Api.homePageArticle}$_pageIndex/json/?cid=$cid");
    var list = articleRes.data?.datas ?? [];
    articleList.addAll(list);
    if (articleRes.isSuccessful) {
      if (list.isNotEmpty) {
        return IndicatorResult.success;
      } else {
        return IndicatorResult.noMore;
      }
    } else {
      return IndicatorResult.fail;
    }
  }

  refreshRequest() async {
    _pageIndex = 0;
    articleList.clear();
    var state = await httpArticleList();
    controller.finishRefresh(state);
  }

  loadMoreRequest() async {
    _pageIndex++;
    var state = await httpArticleList();
    controller.finishLoad(state);
  }
}
